import { BaseOptions } from "../type";


const gap = 20;
// 绘制网格
export class DrawerMesh {
    canvas: HTMLCanvasElement;
    ctx : CanvasRenderingContext2D;

    options?: BaseOptions;

    constructor(canvas: HTMLCanvasElement, options?:BaseOptions){
        this.canvas = canvas;
        this.ctx = canvas.getContext('2d');
        
        if( options ){
            this.options = options;
        }
    }

    private _init(){
        const { _width, _height} = this.options!;

        const { e, f } = this.ctx.getTransform();

        const maxWidth = (_width + Math.abs(e)) / this.options.currentScale ;
        const maxHeight = (_height + Math.abs(f)) / this.options.currentScale ;

        this.ctx.font = '12px Arial';
        this.ctx.fillStyle = 'rgba(0,0,0,1)';

        this.ctx.beginPath();
        this.ctx.strokeStyle = 'rgba(0,0,0,0.5)';

        const startX = (0-e)/this.options.currentScale;
        const startY = (0-f)/this.options.currentScale;
        for(let i = 0; i < maxWidth; i += gap){
            this.ctx.moveTo(i, startY);
            this.ctx.lineTo(i, maxHeight);
        }
        for(let i = 0; i < maxHeight; i += gap){
            this.ctx.fillText(`y=${i}`,maxWidth/2, i+12);
            this.ctx.moveTo(startX, i);
            this.ctx.lineTo(maxWidth, i);
        }
        this.ctx.stroke();
    }

    render(options?: BaseOptions){
        if( options ) this.options = options;
        this._init();
    }
}